package com.cloud.point.concurrent.general;

import java.lang.reflect.Field;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

/**
 * Unsafe类的使用
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-21 15:53
 */
@Slf4j
public class TestUnsafe {
    static Unsafe unsafe;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            //变量是类的成员变量时，不用传递运行时类的对象
            unsafe = (Unsafe) field.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        log.info("{}", unsafe);
        /**
         * 1. 获取域的偏移地址
         */
        long idOffset = unsafe.objectFieldOffset(Stu.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Stu.class.getDeclaredField("name"));
        Stu stu = new Stu();
        /**
         * 2. 原子操作
         */
        unsafe.compareAndSwapInt(stu, idOffset, 0, 233);
        unsafe.compareAndSwapObject(stu, nameOffset, null, "233");
        log.info("{}", stu);

    }

    @Data
    static class Stu {
        private volatile int id;
        private volatile String name;

    }

}

